import Vue from 'vue'
import VueRouter from "vue-router";
import Login from "@/views/login/login"
import Regist from "@/views/login/regist"
import LockScreen from "@/views/login/lockScreen"
import Home from "@/views/home/home"
import ImageList from "@/views/home/imageList"
import Upload from "@/views/home/upload"
import CONST from "@/const/const"

Vue.use(VueRouter)
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

const routes = [
    {
        path: '/login',
        name: 'login',
        component: Login,
    },
    {
        path: '/regist',
        name: 'regist',
        component: Regist,
    },
    {
        path: '/',
        name: 'Home',
        component: Home,
        children: [
            {
                path: 'upload',
                name: 'Upload',
                component: Upload
            },
            {
                path: 'imagelist',
                name: 'ImageList',
                component: ImageList
            },
        ]
    },
    {
        path: '/lockScreen',
        name: 'lockScreen',
        component: LockScreen,
    },
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

router.beforeEach((to, from, next) => {
    const nextRoute = ['Upload', 'ImageList'];
    let isLogin = CONST.isLogin;
    if (nextRoute.indexOf(to.name) >= 0) {
        if (isLogin === "false") {
            router.push('login').then(r => r)
        }
    }
    if (to.name === 'login') {
        if (isLogin === "true") {
            router.push('/').then(r => r);
        }
    }
    next();
});

export default router
